import os
import time
import subprocess
import tkinter as tk
from tkinter import messagebox, filedialog
from tkinter.ttk import Combobox
from tkcalendar import DateEntry

def change_file_times(file_path, new_time):
    formatted_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(new_time))
    try:
        os.utime(file_path, (new_time, new_time))
        if os.name == 'nt':
            powershell_command = f'(Get-Item "{file_path}").CreationTime = "{formatted_time}"'
            subprocess.run(['powershell', '-Command', powershell_command], check=True)
        update_status(f"已成功更新文件 '{file_path}' 的所有时间至 {formatted_time}。")
    except OSError as e:
        update_status(f"更新文件 '{file_path}' 时间失败: {e}")
    except subprocess.CalledProcessError as e:
        update_status(f"设置文件 '{file_path}' 创建时间失败: {e}")

def browse_files():
    filename = filedialog.askopenfilename(
        initialdir="/",
        title="选择文件",
        filetypes=(("所有文件", "*.*"),)
    )
    if filename:
        entry_file_path.delete(0, tk.END)
        entry_file_path.insert(tk.END, filename)

def get_selected_time():
    date_str = date_entry.get()
    hour = hour_combobox.get()
    minute = minute_combobox.get()
    second = second_combobox.get()  # 获取秒数
    return f"{date_str} {hour}:{minute}:{second}"

def update_file_times():
    target_file = entry_file_path.get().strip()
    if not os.path.isfile(target_file):
        messagebox.showerror("错误", f"'{target_file}' 不是有效的文件路径。")
        return
    
    try:
        new_time_str = get_selected_time()
        new_time = time.mktime(time.strptime(new_time_str, '%Y-%m-%d %H:%M:%S'))
        change_file_times(target_file, new_time)
    except ValueError:
        messagebox.showerror("错误", "请按照正确的格式输入日期时间。")

def update_status(message):
    global status_label
    status_label.config(text=message)

def close_window():
    root.destroy()

def animate_status():
    global status_label
    status_label.config(bg="yellow")
    root.after(400, lambda: status_label.config(bg="green"))

# 创建主窗口
root = tk.Tk()
author = "作者: 蓝谷IT"
root.title(f"文件时间修改器 - {author}")
root.geometry("400x200")  # 增加了窗口高度以适应新的状态标签

# 设置窗口图标
try:
    root.iconbitmap('./logo.ico')
except tk.TclError:
    print("未能加载图标文件，请检查路径是否正确。")

# 文件路径输入框和浏览按钮
frame_file = tk.Frame(root)
frame_file.grid(row=0, column=0, padx=10, pady=10, sticky="ew")

label_file_path = tk.Label(frame_file, text="文件路径:")
label_file_path.pack(side=tk.LEFT)

entry_file_path = tk.Entry(frame_file, width=35)
entry_file_path.pack(side=tk.LEFT, padx=(5, 0))

button_browse = tk.Button(frame_file, text="浏览...", command=browse_files)
button_browse.pack(side=tk.LEFT, padx=(5, 0))

# 新的日期时间选择器
frame_new_time = tk.Frame(root)
frame_new_time.grid(row=1, column=0, padx=10, pady=10, sticky="ew")

label_new_time = tk.Label(frame_new_time, text="新的日期时间:")
label_new_time.pack(side=tk.LEFT)

date_entry = DateEntry(frame_new_time, width=12, background='darkblue',
                       foreground='white', borderwidth=2, date_pattern='yyyy-mm-dd')
date_entry.pack(side=tk.LEFT, padx=(5, 0))

hours = [f"{i:02}" for i in range(24)]
minutes = [f"{i:02}" for i in range(60)]
seconds = [f"{i:02}" for i in range(60)]

hour_combobox = Combobox(frame_new_time, values=hours, width=5)
hour_combobox.current(0)  # 设置默认值为第一个小时
hour_combobox.pack(side=tk.LEFT, padx=(5, 0))

minute_combobox = Combobox(frame_new_time, values=minutes, width=5)
minute_combobox.current(0)  # 设置默认值为第一分钟
minute_combobox.pack(side=tk.LEFT, padx=(5, 0))

second_combobox = Combobox(frame_new_time, values=seconds, width=5)
second_combobox.current(0)  # 设置默认值为第一秒
second_combobox.pack(side=tk.LEFT, padx=(5, 0))

# 更新按钮和关闭按钮框架
frame_buttons = tk.Frame(root)
frame_buttons.grid(row=2, column=0, columnspan=2, padx=10, pady=10, sticky="ew")

# 更新按钮
button_update = tk.Button(frame_buttons, text="更新文件时间", command=lambda: [update_file_times(), animate_status()])
button_update.pack(side=tk.LEFT, fill=tk.X, expand=True)

# 关闭按钮
button_close = tk.Button(frame_buttons, text="关闭", command=close_window)
button_close.pack(side=tk.RIGHT, fill=tk.X, expand=True)

# 状态标签
global status_label
status_label = tk.Label(root, text="", bd=1, relief=tk.SUNKEN, anchor=tk.W, justify=tk.LEFT, wraplength=380)
status_label.grid(row=3, column=0, columnspan=2, sticky="ew", padx=10, pady=10)

# 运行主循环
root.mainloop()